#!/usr/bin/env python
# -*- coding: utf-8 -*-

# forever mako


import os,time

import ExecCommand.Public.CommandManager as CmdManager
import MainLoop.Modual as MLoop

ExecLocals=locals()

class Engine:
    def __init__(self):
        self.Moduals=[]

    def StartEngine(self):
        CmdManager.CommandManager.RegisterCommand("Stop",self.ExecCommand)
        CmdManager.CommandManager.RegisterDefaultCommand(self.DefaultExecCommand)
        MLoop.MainLoop.RegisterTimeEvent(0.1,CmdManager.CommandManager.Excute)
        
        RootDir =(os.path.split(os.path.realpath(__file__))[0])
        for Parent,Dirnames,Filenames in os.walk(RootDir):
            for Filename in Filenames:
                FullPath=os.path.join(Parent,Filename)
                Modual=FullPath[len(RootDir)-len(FullPath)+1:].replace("/",".")
                if len(Modual)>9 and Modual[-9:]=='Modual.py':
                    try:
                        cmd="import "+Modual[:-3]+" as M"
                        exec(cmd)
                        if M:
                            self.Moduals.append(M)
                    except Exception as e:
                        print(e)
        MLoop.MainLoop.BeginLoop()
                    
    def StopEngine(self):
        MLoop.MainLoop.EndLoop()
        for M in self.Moduals:
            try:
                M.StopModual()
            except:
                pass
            
    def ExecCommand(self,Command):
        if Command.split(' ')[0]=="Stop":
            self.StopEngine()
            
    def DefaultExecCommand(self,Command):
        global ExecLocals
        exec(Command,globals(),ExecLocals)
            
###
    

if __name__=='__main__':
    E = Engine()
    E.StartEngine()